package servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@WebServlet("/getAuthorInfo")
public class AuthorInfoServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 从请求中拿到所查看的 blogId
        String blogId = req.getParameter("blogId");
        resp.setContentType("text/html; charset=utf8");
        if(blogId == null) {
            resp.getWriter().write("请求中缺少blogId !");
            return;
        }
        // 根据 blogId 从数据库中查找是否存在 对应的Blog对象
        BlogDao blogDao = new BlogDao();
        Blog blog = blogDao.getBlog(Integer.parseInt(blogId));
        if(blog == null) {
            resp.getWriter().write("blogId没找到 !");
            return;
        }

        // 根据 blog对象中的userId查询对应的User对象
        UserDao userDao = new UserDao();
        User user = userDao.getUserById(blog.getUserId());
        if (user == null) {
            resp.getWriter().write("找不到该用户!");
            return;
        }

        // 将拿到的user对象作为响应返回给客户端
        user.setPassword("");
        ObjectMapper objectMapper = new ObjectMapper();
        resp.setContentType("application/json; charset=utf8");
        String respJson = objectMapper.writeValueAsString(user);
        resp.getWriter().write(respJson);
    }
}
